package top.dotgo.web.base.config.feign;

import feign.Feign;
import feign.codec.Decoder;
import feign.codec.Encoder;
import okhttp3.ConnectionPool;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @author jornl
 * @date 2020/2/9 23:49 星期日
 */
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class FeignOkHttpConfig {


    @Bean
    public okhttp3.OkHttpClient okHttpClient() {
        return new okhttp3.OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool())
                .build();
    }


    @Bean
    public Decoder feignDecoder(HttpMessageConverters fastJsonHttpMessageConverter) {
        ObjectFactory<HttpMessageConverters> objectFactory = () -> fastJsonHttpMessageConverter;
        return new SpringDecoder(objectFactory);
    }


    @Bean
    public Encoder feignEncoder(HttpMessageConverters fastJsonHttpMessageConverter) {
        ObjectFactory<HttpMessageConverters> objectFactory = () -> fastJsonHttpMessageConverter;
        return new SpringEncoder(objectFactory);
    }
}
